import 'package:ed25519_hd_key/ed25519_hd_key.dart';
import 'package:flutter/material.dart';
import 'package:hex/hex.dart';
import 'package:itoken/Components/From/CFrom.dart';
import 'package:itoken/Components/From/CInput.dart';
import 'package:itoken/Modle/MAddress.dart';
import 'package:itoken/Store/SAddress.dart';
import 'package:provider/provider.dart';
import 'package:bip39/bip39.dart' as bip39;
import 'package:web3dart/credentials.dart';

enum ImportMold {
  Mnemonic,
  Private,
}

class PImport extends StatelessWidget {
  final ImportMold type;
  PImport({
    @required this.type,
  });
  Future submit(BuildContext context) async {
    CFromStore _CFromStore = Provider.of<CFromStore>(context);
    Map<String, String> data = await _CFromStore.submit();
    print(data);
    String privateKey;
    switch (type) {
      case ImportMold.Mnemonic:
        String seed = bip39.mnemonicToSeedHex(data["string"]);
        KeyData master = ED25519_HD_KEY.getMasterKeyFromSeed(seed);
        privateKey = HEX.encode(master.key);
        print('私钥 ====> $privateKey');

        break;
      case ImportMold.Private:
        privateKey = data["string"];
        print('私钥 ====> $privateKey');
        break;
      default:
    }
    final private = EthPrivateKey.fromHex(privateKey);
    final address = await private.extractAddress();
    SAddress saddress = Provider.of<SAddress>(context);
    saddress.add(MAddress.fromMap({
      "address": address.toString(),
      "private": "$privateKey",
      "mnemonic": ""
    }));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("导入钱包"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CFrom(
              builder: (BuildContext context) {
                return Column(
                  children: <Widget>[
                    CInput(
                      name: "string",
                    ),
                    RaisedButton(
                      onPressed: () {
                        submit(context);
                      },
                      child: Text("导入"),
                    )
                  ],
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
